const base64 = require("./base64");
const sha256 = require("./sha256");
const ResponseMessage = require("../response/message");


// JWT 生成
exports.sign = function (header, payload, secret) {
  const headerBase64 = base64.urlEncode(JSON.stringify(header));
  const payloadBase64 = base64.urlEncode(JSON.stringify(payload));
  const headerAndpayload = headerBase64 + "." + payloadBase64;
  const secretBase64 = sha256.sha256Encode(headerAndpayload + secret);
  return headerBase64 + "." + payloadBase64 + "." + secretBase64;
};

// JWT 校验
exports.verify = function (token, secret) {
  try{
    if (token) {
      const jwtDecode = token.split(".");
      const payload = JSON.parse(base64.urlDecode(jwtDecode[1]));
      if (
        sha256.sha256Encode(jwtDecode[0] + "." + jwtDecode[1] + secret) ===
        jwtDecode[2]
      ) {
        if (payload.expire < Date.now()) {
          return  new ResponseMessage(0,"token 已过期",{})
        } else {
          return new ResponseMessage(2,"token 合法",payload)
        }
      } else {
        return new ResponseMessage(1,"token 不合法",{})
      }
    } else {
      return new ResponseMessage(-1,"token 缺失",{})
    }
  }catch(err){
    return new ResponseMessage(1,"token 不合法",{})
  }
};
